#include <iostream>  
#include <cstring>  
#include <sys/socket.h>  
#include <arpa/inet.h>  
#include <unistd.h>  
#include <thread>  
#include <chrono>  
#include <ctime>  
  
void server_thread() {  
    int server_fd, new_socket;  
    struct sockaddr_in address;  
    int opt = 1;  
    int addrlen = sizeof(address);  
    char buffer[1024] = {0};  
    const char *hello = "Hello from server";  
  
    // 创建 socket 文件描述符  
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {  
        std::cerr << "socket failed" << std::endl;  
        exit(EXIT_FAILURE);  
    }  
  
    // 设置 socket 选项  
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {  
        std::cerr << "setsockopt" << std::endl;  
        exit(EXIT_FAILURE);  
    }  
    address.sin_family = AF_INET;  
    address.sin_addr.s_addr = INADDR_ANY;  
    address.sin_port = htons(9000);  
  
    // 绑定 socket 到端口  
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {  
        std::cerr << "bind failed" << std::endl;  
        exit(EXIT_FAILURE);  
    }  
    if (listen(server_fd, 3) < 0) {  
        std::cerr << "listen" << std::endl;  
        exit(EXIT_FAILURE);  
    }  
  
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {  
        std::cerr << "accept" << std::endl;  
        exit(EXIT_FAILURE);  
    }  
  
    // 发送欢迎消息给客户端  
    send(new_socket, hello, strlen(hello), 0);  
    std::cout << "Hello message sent" << std::endl;  
  
    // 设置超时  
    fd_set readfds;  
    struct timeval tv;  
    int retval;  
  
    // 初始化文件描述符集合  
    FD_ZERO(&readfds);  
    FD_SET(new_socket, &readfds);  
  
    // 设置超时时间  
    tv.tv_sec = 5;  // 5 秒  
    tv.tv_usec = 0; // 0 微秒  
  
    // 等待数据，直到超时  
    retval = select(new_socket + 1, &readfds, NULL, NULL, &tv);  
    if (retval == -1) {  
        std::cerr << "select() failed" << std::endl;  
    } else if (retval) {  
        // 数据可读  
        int valread = read(new_socket, buffer, 1024);  
        std::cout << "Read " << valread << " bytes: " << buffer << std::endl;  
    } else {  
        // 超时  
        std::cout << "Timeout occurred" << std::endl;  
    }  
  
    close(new_socket);  
    close(server_fd);  
}  
  
int main() {  
    std::thread server_thread_obj(server_thread);  
    server_thread_obj.join();  
    return 0;  
}
